package com.xingkeduo.business.operation.domain;

import com.google.common.collect.Lists;
import com.xingkeduo.business.operation.service.ManagerService;
import com.xingkeduo.business.operation.service.PermsService;
import com.xingkeduo.business.operation.service.PostsPermsService;
import com.xingkeduo.pojo.query.ManagerQuery;
import com.xingkeduo.pojo.query.PermsQuery;
import com.xingkeduo.pojo.query.PostsPermsQuery;
import com.xingkeduo.pojo.table.ManagerTable;
import com.xingkeduo.pojo.table.PermsTable;
import com.xingkeduo.pojo.table.PostsPermsTable;
import com.xingkeduo.util.pojo.domain.Page;
import com.xingkeduo.util.pojo.enums.YesNoEnum;
import com.xingkeduo.util.pojo.exception.BusinessException;
import com.xingkeduo.util.pojo.exception.DataException;
import com.xingkeduo.util.tool.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 商户domain
 *
 * @author wangxilong <wangxilong@xingkeduo.com>
 * @version id:v0.1 ${date}${time}
 * @package BeautyOS
 * @copyright Copyright (c) XKD 2019
 */
@Component
public class PermsDomain {

    @Autowired
    private PermsService permsService;

    @Autowired
    private ManagerService managerService;

    @Autowired
    private PostsPermsService postsPermsService;

    public PermsTable getPermsById(Long id) throws Throwable {

        PermsTable permsTable = permsService.selectById(id);

        return permsTable;
    }

    public int createPerms(PermsTable permsTable) throws Throwable {
        if(!CommonUtil.isEmpty(permsTable.getName())){
            List<PermsTable> permsTables = permsService.selectLists(new PermsQuery().setNameRepeat(permsTable.getName()));
            if(!CommonUtil.isEmpty(permsTables)){
                throw new DataException(DataException.Type.DEFAULT, "菜单名字已经存在");
            }
    }

        return permsService.insert(permsTable);
    }

    public int modifyPerms(PermsTable permsTable) throws Throwable {

        PermsTable permsTable1 = permsService.selectById(permsTable.getId());
        if(!CommonUtil.isEmpty(permsTable.getName())){
            if(!permsTable.getName().equals(permsTable1.getName())){
                if(!CommonUtil.isEmpty(permsTable.getName())){
                    List<PermsTable> permsTables = permsService.selectLists(new PermsQuery().setNameRepeat(permsTable.getName()));
                    if(!CommonUtil.isEmpty(permsTables)){
                        throw new DataException(DataException.Type.DEFAULT, "菜单名字已存在");
                    }
                }
            }
        }

        return permsService.update(permsTable);
    }

    //删除
    public int delPerms(Long id) throws Throwable {
        PermsTable permsTable = new PermsTable();

        permsTable.setId(id);
        permsTable.setIsDelete(YesNoEnum.YES);
        int delRes = permsService.delete(permsTable);
        if(delRes > 0){
            return delRes;
        }else{
            throw new DataException(DataException.Type.FAIL, "删除失败");
        }
    }

    public List<PermsTable> getPermsList(PermsQuery permsQuery) throws Throwable {

        List<PermsTable> permsList = permsService.selectLists(permsQuery);

        return permsList;
    }

    //分页查询
    public Page<PermsTable> getPostsPageList(PermsQuery permsQuery) throws Throwable {
        Integer pageNo = permsQuery.getPageNo();
        Integer pageSize = permsQuery.getPageSize();
        Page<PermsTable> postsTablePage = permsService.selectPageLists(permsQuery,pageNo,pageSize);
        return postsTablePage;
    }

    /**
     * 根据用户id获取菜单
     * @version id:v0.1
     *
     * @param userId 参数2 参数2的简短描述
     * @return 返回结果的数据类型 返回结构的描述
     */

    public List<PermsTable> getMenu(Long userId) throws Throwable {
        ManagerTable managerTable = new ManagerTable();
        if(userId != null && userId > 0L){
            managerTable = managerService.selectById(userId);
        }
        List<PostsPermsTable> postsPermsList = new ArrayList<>();
        List<String> permsIdList = new ArrayList<>();
        if(managerTable !=null && managerTable.getPostsId() > 0){
            PostsPermsQuery postsPermsQuery = new PostsPermsQuery();
            postsPermsQuery.setPostsId(managerTable.getPostsId());
            postsPermsList= postsPermsService.selectLists(postsPermsQuery);

            if(!CommonUtil.isEmpty(postsPermsList) && !CommonUtil.isEmpty(postsPermsList.get(0))){
                PostsPermsTable postsPermsTable = postsPermsList.get(0);
                permsIdList =  CollectionUtils.arrayToList(postsPermsTable.getPermsIds().split(","));
            }

        }else{
            throw new BusinessException(BusinessException.Type.DEFAULT, "用户信息不存在");
        }

        //1.获取顶级菜单模块
        List<PermsTable> selectTopLists = permsService.selectLists(new PermsQuery().setPid(0L).setType(1));

        // 3.查询当前用户所有菜单类型(type=2)的菜单
        List<PermsTable> type2PermsList = permsService.selectLists(new PermsQuery().setType(2));

        List<PermsTable> sysList = Lists.newArrayList();
        List<PermsTable> userPermissionType2List = Lists.newArrayList();  // 当前用户所拥有的二级菜单
        //超级管理员
        if(managerTable.getIsadmin() == 1){
            sysList = selectTopLists;
            userPermissionType2List = type2PermsList;
        }
        //普通管理员
        else{
            if(permsIdList.size() > 0){
                for (String permsId : permsIdList) {
                    for(PermsTable system : selectTopLists) {
                        Long id =  Long.valueOf(permsId);
                        if (id.longValue() == system.getId()){
                            sysList.add(system);
                            continue;
                        }

                    }

                    for(PermsTable entity : type2PermsList) {
                        //TODO 处理用户权限对象
                        Long id =  Long.valueOf(permsId);
                        if (id.longValue() == entity.getId()){
                            userPermissionType2List.add(entity);
                            continue;
                        }
                    }
                }

            }
        }


        // 4.获取一级菜单和子菜单
        List<PermsTable> permsTableList = Lists.newArrayList();
        for(PermsTable entity : sysList) {
            // 如果当前角色有此一级菜单，则查询此一级菜单下所有子菜单
            List<PermsTable> childList = this.getChildrenMenu(entity.getId(), userPermissionType2List);
            Collections.sort(childList, Comparator.comparing(PermsTable::getSort));
            entity.setChildren(childList);
            // 组装新的一级菜单(包括子菜单)返回前端
            permsTableList.add(entity);

        }
        return permsTableList;
    }


    public List<PermsTable> getMenuByPid(Long pid) throws Throwable {
        //1.获取顶级菜单模块
        PermsQuery permsTopQuery = new PermsQuery();
        permsTopQuery.setPid(pid).setType(1);
        List<PermsTable> selectTopLists = permsService.selectLists(permsTopQuery);

        // 3.查询当前用户所有菜单类型(type=2)的菜单
        PermsQuery permsQuery = new PermsQuery();
        permsQuery.setIsdelete(1).setType(2);

        List<PermsTable> typePermsList = permsService.selectLists(permsQuery);

        // 4.获取一级菜单子菜单
        List<PermsTable> permsTableList = Lists.newArrayList();
        for(PermsTable entity : selectTopLists) {
            // 如果当前角色有此一级菜单，则查询此一级菜单下所有子菜单
            List<PermsTable> childList = getChildrenMenu(entity.getId(), typePermsList);
            Collections.sort(childList, Comparator.comparing(PermsTable::getSort));
            entity.setChildren(childList);
            // 组装新的一级菜单(包括子菜单)返回前端
            permsTableList.add(entity);
        }

        return permsTableList;
    }

    // 递归获取子菜单
    private List<PermsTable> getChildrenMenu(Long parentId, List<PermsTable> list) {
        List<PermsTable> childList = Lists.newArrayList();    // 子菜单
        for(PermsTable entity : list) {
            if(entity.getPid() == null) {
                continue;
            }
            if(entity.getPid().equals(parentId)) {
                childList.add(entity);
            }
        }

        for(PermsTable entity : childList) {
//            if(StringUtils.isNotBlank(entity.getUri())) { todo
//                continue;
//            }
            // 如果菜单的uri为空，则继续递归子菜单
            entity.setChildren(getChildrenMenu(entity.getId(), list));
        }
        if (CollectionUtils.isEmpty(childList)) {
            return Collections.emptyList();
        }
        return childList;
    }

}
